const express = require('express');
const { Op, sequelize } = require('sequelize');
const { News } = require('../models');

const router = express.Router();

// 获取新闻列表
router.get('/', async (req, res) => {
  try {
    const {
      category,
      keyword,
      page = 1,
      pageSize = 10,
      status = 'published'
    } = req.query;

    // 构建查询条件
    const where = {
      status: status
    };

    // 按分类筛选
    if (category && category !== '') {
      where.category = category;
    }

    // 按关键词搜索
    if (keyword && keyword !== '') {
      where[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { summary: { [Op.like]: `%${keyword}%` } }
      ];
    }

    // 分页参数
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);
    const offset = (pageNum - 1) * pageSizeNum;

    // 查询数据
    const { count, rows } = await News.findAndCountAll({
      where,
      order: [['publishDate', 'DESC']],
      limit: pageSizeNum,
      offset: offset,
      attributes: [
        'id',
        'title',
        'summary',
        'category',
        'image',
        'publishDate',
        'views',
        'author'
      ]
    });

    // 返回结果
    res.json({
      code: 200,
      message: 'success',
      data: {
        list: rows,
        total: count,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages: Math.ceil(count / pageSizeNum)
      }
    });

  } catch (error) {
    console.error('获取新闻列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取新闻列表失败',
      error: error.message
    });
  }
});

// 获取新闻详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // 查找新闻详情
    const news = await News.findByPk(id, {
      where: { status: 'published' }
    });

    if (!news) {
      return res.status(404).json({
        code: 404,
        message: '新闻不存在'
      });
    }

    // 增加阅读量
    await news.increment('views');

    // 获取相关新闻（同类别，排除当前新闻）
    const relatedNews = await News.findAll({
      where: {
        category: news.category,
        id: { [Op.ne]: news.id },
        status: 'published'
      },
      order: [['publishDate', 'DESC']],
      limit: 3,
      attributes: [
        'id',
        'title',
        'summary',
        'category',
        'image',
        'publishDate',
        'views',
        'author'
      ]
    });

    res.json({
      code: 200,
      message: 'success',
      data: {
        news,
        relatedNews
      }
    });

  } catch (error) {
    console.error('获取新闻详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取新闻详情失败',
      error: error.message
    });
  }
});

// 获取新闻分类统计
router.get('/categories/stats', async (req, res) => {
  try {
    const stats = await News.findAll({
      where: { status: 'published' },
      attributes: [
        'category',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['category'],
      order: [[sequelize.fn('COUNT', sequelize.col('id')), 'DESC']]
    });

    res.json({
      code: 200,
      message: 'success',
      data: stats
    });

  } catch (error) {
    console.error('获取新闻分类统计失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取新闻分类统计失败',
      error: error.message
    });
  }
});

// 获取热门新闻
router.get('/popular/list', async (req, res) => {
  try {
    const { limit = 5 } = req.query;

    const popularNews = await News.findAll({
      where: { status: 'published' },
      order: [['views', 'DESC']],
      limit: parseInt(limit),
      attributes: [
        'id',
        'title',
        'summary',
        'category',
        'image',
        'publishDate',
        'views',
        'author'
      ]
    });

    res.json({
      code: 200,
      message: 'success',
      data: popularNews
    });

  } catch (error) {
    console.error('获取热门新闻失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取热门新闻失败',
      error: error.message
    });
  }
});

module.exports = router; 